package org.raymond.iworks.study.netty.atguigu.nio.reactor.mainsub;

import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.List;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class ReadNotifyWorker {
    private List<SocketChannel> notifyList;

    public ReadNotifyWorker(List<SocketChannel> notifyList){
        this.notifyList = notifyList;
    }

    /**
     * 转发消息到其他客户端
     * msg 消息
     */
    public void notifyOtherClient(String msg)  {
        log.info("服务器转发消息~");
        for (SocketChannel socketChannel : notifyList) {
            //通过消息，包裹获取一个缓冲区
            ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
            String remote = null;
            try {
                remote = socketChannel.getRemoteAddress().toString();
                socketChannel.write(byteBuffer);
            } catch (Exception e) {
                log.error("转发->{} 失败: {}", remote, e.getMessage());
            }
        }
    }
}
